# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：商品的curd
"""
from models.base import Goods, Category, Attribute
from schemas.goods import GoodAddSchemas, GoodSchemas, AttrSchemas
from fastapi import HTTPException


async def add_good_curd(post: GoodAddSchemas) -> GoodSchemas:
    if await Goods.exists(name=post.name):
        raise HTTPException(status_code=422, detail="该商品已存在！")
    if post.state not in [0, 1, 2]:
        raise HTTPException(status_code=422, detail="商品状态参数错误！")
    if post.is_promote not in [0, 1]:
        raise HTTPException(status_code=422, detail="商品是否畅销参数错误！")
    if not await Category.exists(id=post.cid_one_id):
        raise HTTPException(status_code=422, detail="该一级分类不存在！")
    if not await Category.exists(id=post.cid_two_id):
        raise HTTPException(status_code=422, detail="该二级分类不存在！")
    if not await Category.exists(id=post.cid_three_id):
        raise HTTPException(status_code=422, detail="该三级分类不存在！")
    static_attrs_list = []
    if post.static_attrs:
        for attr in post.static_attrs:
            if not await Attribute.exists(id=attr, _type="static"):
                raise HTTPException(status_code=422, detail="该静态属性不存在！")
            attr_obj = await Attribute.get(id=attr)
            if attr_obj.cid_id != post.cid_three_id:
                raise HTTPException(status_code=422, detail="该静态属性不属于你输入的该三级分类下！")
            static_attrs_list.append(attr_obj)
    dynamic_attrs_list = []
    if post.dynamic_attrs:
        for attr in post.dynamic_attrs:
            if not await Attribute.exists(id=attr, _type="dynamic"):
                raise HTTPException(status_code=422, detail="该动态属性值不存在！")
            attr_obj = await Attribute.get(id=attr)
            if attr_obj.cid_id != post.cid_three_id:
                raise HTTPException(status_code=422, detail="该动态属性不属于你输入的该三级分类下！")
            dynamic_attrs_list.append(attr_obj)
    good = await Goods.create(name=post.name, price=post.price, number=post.number, introduce=post.introduce,
                              big_log=post.big_log, small_log=post.small_log, state=post.state,
                              is_promote=post.is_promote,
                              hot_number=post.hot_number, weight=post.weight, cid_one_id=post.cid_one_id,
                              cid_two_id=post.cid_two_id, cid_three_id=post.cid_three_id)
    await good.static_attrs.add(*static_attrs_list)
    await good.dynamic_attrs.add(*dynamic_attrs_list)
    await good.save()
    return GoodSchemas(**dict(good), static_attrs=[AttrSchemas(**dict(attr)) for attr in static_attrs_list],
                       dynamic_attrs=[AttrSchemas(**dict(attr)) for attr in dynamic_attrs_list])
